import React, { Component } from 'react';
import {nanoid} from 'nanoid';

import {addPerson} from '../../redux/actions/person';

//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'

class Person extends Component {

    addPerson = () => {
        const name = this.nameNode.value;
        const age = this.ageNode.value;
        const personObj = {id: nanoid, name: name, age: age};
        this.props.addPerson(personObj);
        this.nameNode.value = '';
        this.ageNode.value = '';
    }

    render() {
        return (
            <div>  
                <h2>我是Person组件，上方组件求和为：{this.props.count}</h2>
                <input ref={c => this.nameNode = c} type="text" placeholder="输入名字"/>
                <input ref={c => this.ageNode = c} type="text" placeholder="输入年龄"/>
                <button onClick={this.addPerson}>添加</button>
                <ul>
                    {
                        this.props.persons.map((p)=>{
                            return <li key={p.id}>{p.name}---{p.age}</li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

//使用connect()()创建并暴露一个Count的容器组件
export default connect(
	state => ({
        persons: state.persons, 
        count: state.count
    }),
	//mapDispatchToProps的简写
	{
		addPerson
	}
)(Person)